import React, { useState, useEffect } from 'react';
import { Card, Button, Table, Space, Typography, Checkbox, Progress, message, Modal, Tag } from 'antd';
import { DeleteOutlined, ReloadOutlined, ExclamationCircleOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../../i18n/I18nProvider';
import { apiService } from '../../services';
import './NodeModulesCleaner.scss';

const { Title, Paragraph, Text } = Typography;
const { confirm } = Modal;

interface NodeModuleInfo {
  path: string;
  size: number;
  sizeStr: string;
  name?: string;
  isRoot?: boolean;
  timestamp?: number;
  lastAccessed?: string;
  key?: string;
}

interface CleanResult {
  success: boolean;
  errors?: any[];
}

const NodeModulesCleaner: React.FC = () => {
  const { t } = useLanguage();
  const navigate = useNavigate();
  const [nodeModulesList, setNodeModulesList] = useState<NodeModuleInfo[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [selectedPaths, setSelectedPaths] = useState<string[]>([]);
  const [cleaningPaths, setCleaningPaths] = useState<string[]>([]);
  const [progress, setProgress] = useState<number>(0);
  const [showProgress, setShowProgress] = useState<boolean>(false);
  const [messageApi, contextHolder] = message.useMessage();

  // 扫描 node_modules
  const scanNodeModules = async () => {
    try {
      setLoading(true);
      messageApi.loading({ content: t('cleanup.nodeModules.scanning'), key: 'scan', duration: 0 });

      const response = await apiService.cleanup.getNodeModules();
      // 确保响应数据是数组
      const data = Array.isArray(response) ? response : [];

      // 添加 key 属性
      const formattedData = data.map((item: NodeModuleInfo, index: number) => ({
        ...item,
        key: item.path,
        lastAccessed: item.timestamp
          ? new Date(item.timestamp).toLocaleString()
          : undefined
      }));

      setNodeModulesList(formattedData);
      messageApi.success({ content: t('cleanup.nodeModules.scanSuccess'), key: 'scan' });
    } catch (error) {
      console.error('扫描 node_modules 失败:', error);
      messageApi.error({ content: t('cleanup.nodeModules.scanFailed'), key: 'scan' });
    } finally {
      setLoading(false);
    }
  };

  // 清理选中的 node_modules
  const cleanNodeModules = async () => {
    if (selectedPaths.length === 0) {
      messageApi.warning(t('cleanup.nodeModules.noneSelected'));
      return;
    }

    confirm({
      title: t('cleanup.nodeModules.confirmTitle'),
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>{t('cleanup.nodeModules.confirmDesc')}</p>
          <p>{t('cleanup.nodeModules.confirmPaths')}</p>
          <ul className="confirm-paths-list">
            {selectedPaths.map((path) => (
              <li key={path}>{path}</li>
            ))}
          </ul>
        </div>
      ),
      onOk: async () => {
        try {
          setCleaningPaths([...selectedPaths]);
          setShowProgress(true);
          setProgress(0);

          // 模拟进度
          const timer = setInterval(() => {
            setProgress((prev) => {
              const newProgress = prev + Math.random() * 10;
              return newProgress >= 95 ? 95 : newProgress;
            });
          }, 300);

          messageApi.loading({ content: t('cleanup.nodeModules.cleaning'), key: 'clean', duration: 0 });

          // 实际清理操作
          const response = await apiService.cleanup.cleanPath(selectedPaths);
          const result = response as unknown as CleanResult;

          clearInterval(timer);
          setProgress(100);

          if (result.success) {
            messageApi.success({ content: t('cleanup.nodeModules.cleanSuccess'), key: 'clean' });
            // 重新扫描
            setTimeout(() => {
              setShowProgress(false);
              setSelectedPaths([]);
              scanNodeModules();
            }, 1000);
          } else {
            messageApi.error({
              content: t('cleanup.nodeModules.cleanPartialFailed'),
              key: 'clean'
            });
            console.error('清理结果错误:', result.errors);
          }
        } catch (error) {
          setShowProgress(false);
          console.error('清理 node_modules 失败:', error);
          messageApi.error({ content: t('cleanup.nodeModules.cleanFailed'), key: 'clean' });
        }
      },
    });
  };

  // 处理返回按钮点击
  const handleBack = () => {
    navigate('/cleanup');
  };

  // 初始加载
  useEffect(() => {
    scanNodeModules();
  }, []);

  // 表格列定义
  const columns = [
    {
      title: t('cleanup.nodeModules.path'),
      dataIndex: 'path',
      key: 'path',
      render: (text: string, record: NodeModuleInfo) => (
        <Space>
          {record.isRoot && <Tag color="blue">{t('cleanup.nodeModules.root')}</Tag>}
          <Text ellipsis={{ tooltip: text }}>{text}</Text>
        </Space>
      ),
    },
    {
      title: t('cleanup.nodeModules.size'),
      dataIndex: 'sizeStr',
      key: 'sizeStr',
      width: 120,
      render: (text: string, record: NodeModuleInfo) => (
        record.size > 50 * 1024 * 1024
          ? <Text type="danger">{text}</Text>
          : <Text>{text}</Text>
      ),
    },
    {
      title: t('cleanup.nodeModules.lastAccessed'),
      dataIndex: 'lastAccessed',
      key: 'lastAccessed',
      width: 180,
    },
  ];

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys: selectedPaths,
    onChange: (selectedRowKeys: React.Key[]) => {
      setSelectedPaths(selectedRowKeys as string[]);
    },
  };

  return (
    <div className="node-modules-cleaner page-container">
      {contextHolder}
      <div className="page-header">
        <Space className="mb-16">
          <Button icon={<ArrowLeftOutlined />} onClick={handleBack}>
            {t('app.back')}
          </Button>
          <Title level={2} style={{ margin: 0 }}>
            {t('cleanup.nodeModules.title')}
          </Title>
        </Space>
        <Paragraph className="page-description">
          {t('cleanup.nodeModules.pageDesc')}
        </Paragraph>
      </div>

      <Card className="mb-24">
        <Space className="action-bar">
          <Button
            type="primary"
            danger
            icon={<DeleteOutlined />}
            onClick={cleanNodeModules}
            disabled={selectedPaths.length === 0 || loading}
          >
            {t('cleanup.clean')} ({selectedPaths.length})
          </Button>
          <Button
            icon={<ReloadOutlined />}
            onClick={scanNodeModules}
            disabled={loading}
          >
            {t('cleanup.scan')}
          </Button>
          <Checkbox
            onChange={(e) => {
              if (e.target.checked) {
                setSelectedPaths(nodeModulesList.map(item => item.path));
              } else {
                setSelectedPaths([]);
              }
            }}
            checked={selectedPaths.length === nodeModulesList.length && nodeModulesList.length > 0}
            disabled={loading || nodeModulesList.length === 0}
          >
            {t('cleanup.nodeModules.selectAll')}
          </Checkbox>
        </Space>

        {showProgress && (
          <div className="progress-container mb-24">
            <Progress percent={Math.round(progress)} status={progress >= 100 ? 'success' : 'active'} />
            <div className="cleaning-paths">
              {cleaningPaths.map((path) => (
                <Tag key={path} color="processing" className="cleaning-path">
                  {path}
                </Tag>
              ))}
            </div>
          </div>
        )}

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={nodeModulesList}
          loading={loading}
          pagination={false}
          scroll={{ y: 500 }}
          size="middle"
          locale={{
            emptyText: t('cleanup.nodeModules.noNodeModules')
          }}
          summary={(pageData) => {
            if (pageData.length === 0) return null;

            // 计算总大小
            const totalSize = pageData.reduce((acc, curr) => acc + curr.size, 0);
            const totalSizeStr = formatSize(totalSize);

            // 计算选中大小
            const selectedItems = pageData.filter((item) => selectedPaths.includes(item.path));
            const selectedSize = selectedItems.reduce((acc, curr) => acc + curr.size, 0);
            const selectedSizeStr = formatSize(selectedSize);

            return (
              <Table.Summary.Row>
                <Table.Summary.Cell index={0} colSpan={2}>
                  <Text strong>{t('cleanup.nodeModules.totalSize')}:</Text> {totalSizeStr}
                  {selectedPaths.length > 0 && (
                    <Text className="selected-size"> ({t('cleanup.nodeModules.selectedSize')}: {selectedSizeStr})</Text>
                  )}
                </Table.Summary.Cell>
                <Table.Summary.Cell index={1}>
                  <Text strong>{t('cleanup.nodeModules.count')}:</Text> {pageData.length}
                </Table.Summary.Cell>
              </Table.Summary.Row>
            );
          }}
        />
      </Card>
    </div>
  );
};

// 格式化大小
function formatSize(bytes: number): string {
  if (bytes === 0) return '0 B';

  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

export default NodeModulesCleaner;
